<template>
  <view class="container">
    <view class="button">
      <button size="mini" type="primary" @click="conClickRedoQuestion">重做错题</button>
      <button size="mini" type="warn" @click="conClickComposeQuestion">导出错题</button>
    </view>
    <view>
      <block v-for="(item_question, index) in wrongQuestionList" :key="index" class="questionItem">
        <text>{{ index + 1 }}.</text>
        <rich-text :nodes="item_question.content"></rich-text>
        <!-- <view class="images" v-if="item_question.images.length > 0 && item_question.images_scale.length > 0">
          <block v-for="(image_url, index_image) in item_question.images" :key="index_image">
            <image mode="scaleToFill" :style="styleImage(item_question, index_image)" :src="image_url"></image>
          </block>
        </view> -->
      </block>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { QuestionItem } from '@/types/home'
import { getAllWrongQuestionMyselfAPI } from '@/services/home'
import { onLoad, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
import { useMemberStore } from '@/stores'

const memberStore = useMemberStore()
const composeList = ref<QuestionItem[]>([])
const wrongQuestionList = ref<QuestionItem[]>([])
let costPoint = ref<number>(0)
const state = reactive({
  page: 1,
  size: 10,
  total: 1,
})

//重做错问题事件
const conClickRedoQuestion = () => {
  console.log('重做错题啦')
  let questions_amount = wrongQuestionList.value.length
  if (questions_amount > 0) {
    uni.navigateTo({
      url: `/pages/puzzle/exercise_step_two?type=reDdWrongQuestion`,
    })
  } else {
    uni.showToast({ icon: 'error', title: '本栏目暂无题目' })
  }
}

// 获取错题本题目
const getAllWrongQuestionMyselfData = async () => {
  let params_data = { page: state.page, size: state.size }
  let res = await getAllWrongQuestionMyselfAPI(params_data)
  console.log('获取错题结果：', res)
  if (res.code == 200) {
    wrongQuestionList.value = res.data.results.map((item) => item.question_info)
    state.total = res.total
  } else {
    console.log('获取错题本失败', res.message)
    uni.showToast({ icon: 'error', title: '获取错题本失败' })
  }
}
// 增加错题本题目
const addWrongQuestionMyselfData = async () => {
  if (wrongQuestionList.value.length >= state.total) {
    uni.showToast({ icon: 'error', title: '没有更多错题了' })
    return 0
  }
  let params_data = { page: state.page + 1, size: state.size }
  let res = await getAllWrongQuestionMyselfAPI(params_data)
  console.log('获取错题结果：', res)
  if (res.code == 200) {
    wrongQuestionList.value.push(...res.data.results.map((item) => item.question_info))
    state.page += 1
    state.total = res.total
  } else {
    console.log('获取错题本失败', res.message)
    uni.showToast({ icon: 'error', title: '获取错题本失败' })
  }
}
// 页面加载
onLoad(() => {
  getAllWrongQuestionMyselfData()
})
// 自定义下拉刷新被触发
onPullDownRefresh(async () => {
  await Promise.all([getAllWrongQuestionMyselfData()])
  // 停止页面加载动画
  setTimeout(() => {
    uni.stopPullDownRefresh()
  }, 1000)
})
// 自定义触底加载更多数据
// 自定义触底加载更多数据
onReachBottom(async () => {
  console.log('触底拉')
  if (wrongQuestionList.value.length >= state.total) {
    uni.showToast({ title: '没有更多数据了！', icon: 'none' })
  } else {
    addWrongQuestionMyselfData()
  }
})

// 提交组卷，把所有错题发送给后端，返回docx文件流
const conClickComposeQuestion = () => {
  console.log('要组卷错题啦，word文件下载！')
  composeList.value = wrongQuestionList.value
  let bank_point = memberStore.profile!.bank_point
  if (composeList.value.length == 0) {
    uni.showToast({ icon: 'error', title: '先选题哦^_^' })
    return 0
  }
  if (costPoint.value > bank_point) {
    uni.showToast({ icon: 'error', title: '你的库币余额不足，无法组卷' })
    return 0
  }
  // composeList.value = convertQuestionListbr2Enter(composeList.value)
  let question_list_form = []
  // 注意：只能选取指定需要的字段，否则后端会出错
  for (let item of composeList.value) {
    question_list_form.push({
      content: item.content,
      answer: item.answer,
      explain: item.explain,
      type: item.type,
      knowledgepoint: item.knowledgepoint,
      open_level: item.open_level,
      owner: item.owner_info,
      bank_point: item.bank_point,
      id: item.id,
    })
  }

  const currentDate = new Date()
  const paperForm = {
    title: '试卷标题' + String(currentDate.getMonth() + 1) + '月' + currentDate.getDate() + '日',
    description: '写下备注哦',
    is_joint: false,
    open_level: 'private',
    publish: '',
    answer_position: 'detach',
    type_sorted: true,
  }
  let params = {
    questionList: question_list_form,
    paperInformation: paperForm,
  }
  console.log('即将发送到题目列表：', question_list_form)
  console.log('试卷参数：', paperForm)
  uni.showLoading({
    title: '加载中...',
  })
  uni.request({
    url: '/QuestionList2DocxFile/',
    method: 'POST',
    data: params,
    responseType: 'arraybuffer',
    header: {
      token: memberStore.profile?.token,
    },
    success: (res) => {
      uni.hideLoading()
      console.log('服务器返回结果', res)
      if (res.statusCode === 200) {
        const fs = uni.getFileSystemManager()
        fs.writeFile({
          filePath: wx.env.USER_DATA_PATH + '/download.docx',
          data: res.data as ArrayBuffer,
          encoding: 'binary',
          success(res) {
            uni.openDocument({
              showMenu: true,
              filePath: wx.env.USER_DATA_PATH + '/download.docx',
              success: function (res) {
                console.log('打开文档成功！')
              },
            })
          },
        })
      }
    },
    fail: (err) => {
      uni.hideLoading()
      console.log(err)
      uni.showToast({
        icon: 'none',
        mask: true,
        title: '失败请重新下载',
      })
    },
  })
}
</script>

<style lang="scss">
.questionItem {
  font-size: 28rpx;
  display: flex;
  flex-flow: row wrap;
  margin: 2rpx;
}

.button {
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
  align-items: center;
}
</style>
